package com.example.tnot.Teacher.CoursePart.adapter;

import static com.example.tnot.login.fragmentui.LoginFragment.BASE_URL;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.tnot.R;
import com.example.tnot.Teacher.CoursePart.Container.CourseContainerFragmentDirections;
import com.example.tnot.Teacher.CoursePart.ItemBean.rv_MyTeachListItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class rvMyTeachAdapter extends RecyclerView.Adapter<rvMyTeachAdapter.ViewHolder>{
    private List<rv_MyTeachListItem> courses;
    private int CurrentPosition;
    LinearLayout ll_more;
    public static final String BASE_IMAGE_URL = BASE_URL+"api/get_course_avatar/";

    public rvMyTeachAdapter(List<rv_MyTeachListItem> courses) {
        this.courses = courses;
    }

    @NonNull
    @Override
    public rvMyTeachAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item_rv_teacher_teach_course, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull rvMyTeachAdapter.ViewHolder holder, int position) {
        CurrentPosition = holder.getBindingAdapterPosition();
        rv_MyTeachListItem item = courses.get(position);

        //String courseId = getCourseIdFromName(item.getCourse_name());
        String courseId=item.getCourse_id();

        String imageUrl = BASE_IMAGE_URL + courseId;

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.example_face)
                .error(R.drawable.example_face)
                .transform(new CenterCrop(), new RoundedCorners(8));

        Glide.get(holder.itemView.getContext()).clearMemory();  // 清除内存缓存（需在主线程）
        new Thread(() -> {
            // 清除磁盘缓存（需在子线程）
            Glide.get(holder.itemView.getContext()).clearDiskCache();
        }).start();

        Glide.with(holder.itemView.getContext())
                .load(imageUrl)
                .apply(options)
                .into(holder.iv_CourseImage);


        holder.tv_CourseName.setText(item.getCourse_name());
        holder.tv_CourseTeacher.setText(item.getCourse_teacher());

        LinearLayoutManager layoutManager = new LinearLayoutManager(holder.itemView.getContext());
        holder.rv_class.setLayoutManager(layoutManager);

        rv_ClassAdapter classAdapter = null;
        try {
            classAdapter = getRvClassAdapter(item);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        holder.rv_class.setAdapter(classAdapter);

        // 优化性能
        holder.rv_class.setHasFixedSize(true);
        holder.rv_class.setNestedScrollingEnabled(false);

        // 点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("CourseName", item.getCourse_name());

                ArrayList<String> classList = new ArrayList<>(item.getCourse_classes());
                bundle.putString("ClassList", classList.toString());

                bundle.putString("CourseId",item.getCourse_id());
                bundle.putString("CourseTeacher", item.getCourse_teacher());

                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_courseContainerFragment_to_courseDetailFragment, bundle);
            }
        });

        ll_more = holder.itemView.findViewById(R.id.ll_more);
        ll_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @NonNull
    private static rv_ClassAdapter getRvClassAdapter(rv_MyTeachListItem item) throws JSONException {

        List<String> classStrList = item.getCourse_classes();
        JSONArray courseArray = new JSONArray();
        ArrayList<String> courseClasses = new ArrayList<>();

//        for (String classStr : classStrList) {
//
//            JSONObject classObj = new JSONObject(classStr);
//
//            courseArray.put(classObj);
//
//            String className = classObj.getString("classname");
//            //int classNum = classObj.getInt("classnum");
//            courseClasses.add(className);
//        }


        //10.4 11.23报错
        for (String classStr : classStrList) {
            try {
                // 尝试解析为JSON对象
                JSONObject classObj = new JSONObject(classStr);
                String className = classObj.getString("classname");
                courseClasses.add(className);
            } catch (JSONException e) {
                // 如果不是JSON格式，则直接作为班级名称处理
                courseClasses.add(classStr);
            }
        }

        rv_ClassAdapter classAdapter = new rv_ClassAdapter(courseClasses);
        return classAdapter;
    }

    @Override
    public int getItemCount() {
        return courses == null ? 0 : courses.size();  // 优化：避免空指针
    }


    public static class ViewHolder extends RecyclerView.ViewHolder{
        public ImageView iv_CourseImage;
        public TextView tv_CourseName, tv_CourseTeacher;
        public RecyclerView rv_class;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_CourseImage = itemView.findViewById(R.id.iv_CourseImage);
            tv_CourseName = itemView.findViewById(R.id.tv_CourseName);
            tv_CourseTeacher = itemView.findViewById(R.id.tv_CourseTeacher);
            rv_class = itemView.findViewById(R.id.rv_class);
        }
    }

    public static class MarginItemDecoration extends RecyclerView.ItemDecoration {
        private int marginleft;
        private int marginright;
        private int margintop;
        private int marginbottom;

        public MarginItemDecoration(int margintop, int marginbottom,int marginleft, int marginright) {
            this.marginleft = marginleft;
            this.marginright = marginright;
            this.margintop = margintop;
            this.marginbottom = marginbottom;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            outRect.left = marginleft;
            outRect.right = marginright;
            outRect.top = margintop;
            int position = parent.getChildLayoutPosition(view);
            if (position != state.getItemCount() - 1) {
                outRect.bottom = marginbottom;
            }
        }
    }
}